/**
 * 提纲面板组件
 * 管理提纲生成、展示和导出
 */

import React, { useState } from 'react';
import {
  Card,
  Button,
  Space,
  Select,
  InputNumber,
  message,
  Tree,
  Tag,
  Collapse,
  Statistic,
  Row,
  Col,
  Modal,
  Input,
} from 'antd';
import {
  ThunderboltOutlined,
  DownloadOutlined,
  EditOutlined,
  FileTextOutlined,
  CheckCircleOutlined,
} from '@ant-design/icons';
import type { DataNode } from 'antd/es/tree';
import { useBrainstormStore } from '@/stores/brainstorm.store';
import { outlineGeneratorService } from '@/services/outline-generator.service';
import { OutlineStyle, OutlineNode } from '@/types/brainstorm';
import './style.css';

const { Option } = Select;
const { Panel } = Collapse;
const { TextArea } = Input;

interface OutlinePanelProps {
  onContinue?: () => void;
}

export const OutlinePanel: React.FC<OutlinePanelProps> = ({ onContinue }) => {
  const { currentSession, setOutline } = useBrainstormStore();
  const [generating, setGenerating] = useState(false);
  const [style, setStyle] = useState<OutlineStyle>('academic');
  const [targetWordCount, setTargetWordCount] = useState(3000);
  const [selectedTitle, setSelectedTitle] = useState(0);

  const outline = currentSession?.outline;
  const selectedViewpoints = currentSession?.viewpoints.filter((v) => v.completed) || [];

  // 生成提纲
  const handleGenerate = async () => {
    if (!currentSession) {
      message.error('当前没有活跃会话');
      return;
    }

    if (selectedViewpoints.length === 0) {
      message.warning('请先选择至少一个观点');
      return;
    }

    setGenerating(true);
    try {
      const generatedOutline = await outlineGeneratorService.generateOutline({
        sessionId: currentSession.id,
        selectedViewpoints,
        style,
        targetWordCount,
      });

      setOutline(generatedOutline);
      message.success('提纲生成成功！');
    } catch (error) {
      console.error('生成提纲失败:', error);
      message.error('生成提纲失败，请稍后重试');
    } finally {
      setGenerating(false);
    }
  };

  // 导出为Markdown
  const handleExportMarkdown = () => {
    if (!outline) {
      message.warning('请先生成提纲');
      return;
    }

    const markdown = outlineGeneratorService.exportAsMarkdown(outline);
    const blob = new Blob([markdown], { type: 'text/markdown' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = `${outline.titleSuggestions[selectedTitle] || '提纲'}.md`;
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    message.success('导出成功！');
  };

  // 转换为Tree数据格式
  const convertToTreeData = (nodes: OutlineNode[]): DataNode[] => {
    return nodes.map((node) => ({
      key: node.id,
      title: (
        <div className="outline-node">
          <span className="node-title">{node.title}</span>
          <Space size="small" style={{ marginLeft: 8 }}>
            <Tag color={node.status === 'completed' ? 'success' : 'default'}>
              {node.estimatedWords}字
            </Tag>
            {node.keywords?.map((kw) => (
              <Tag key={kw} color="blue">
                {kw}
              </Tag>
            ))}
          </Space>
        </div>
      ),
      children: node.children ? convertToTreeData(node.children) : undefined,
    }));
  };

  // 渲染控制面板
  const renderControlPanel = () => (
    <Card className="control-panel" title="生成设置" bordered={false}>
      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
        {/* 风格选择 */}
        <div className="control-item">
          <label className="control-label">提纲风格:</label>
          <Select value={style} onChange={setStyle} style={{ width: '100%' }}>
            <Option value="academic">学术论文式</Option>
            <Option value="news">新闻报道式</Option>
            <Option value="story">故事叙述式</Option>
            <Option value="marketing">营销文案式</Option>
            <Option value="tutorial">教程指南式</Option>
          </Select>
        </div>

        {/* 目标字数 */}
        <div className="control-item">
          <label className="control-label">目标字数:</label>
          <InputNumber
            value={targetWordCount}
            onChange={(value) => setTargetWordCount(value || 3000)}
            min={500}
            max={50000}
            step={500}
            style={{ width: '100%' }}
            addonAfter="字"
          />
        </div>

        {/* 操作按钮 */}
        <Space>
          <Button
            type="primary"
            icon={<ThunderboltOutlined />}
            onClick={handleGenerate}
            loading={generating}
            disabled={selectedViewpoints.length === 0}
          >
            生成提纲
          </Button>
          {outline && (
            <>
              <Button icon={<DownloadOutlined />} onClick={handleExportMarkdown}>
                导出Markdown
              </Button>
              <Button icon={<EditOutlined />} disabled>
                编辑提纲
              </Button>
            </>
          )}
        </Space>
      </Space>
    </Card>
  );

  // 渲染统计信息
  const renderStats = () => {
    if (!outline) return null;

    const totalNodes = outline.nodes.length;
    const totalWords = outline.totalEstimatedWords;

    return (
      <Card className="stats-card" bordered={false}>
        <Row gutter={16}>
          <Col span={8}>
            <Statistic title="章节总数" value={totalNodes} prefix={<FileTextOutlined />} />
          </Col>
          <Col span={8}>
            <Statistic
              title="预计字数"
              value={totalWords}
              suffix="字"
              prefix={<EditOutlined />}
            />
          </Col>
          <Col span={8}>
            <Statistic
              title="标题备选"
              value={outline.titleSuggestions.length}
              prefix={<CheckCircleOutlined />}
            />
          </Col>
        </Row>
      </Card>
    );
  };

  // 渲染标题选择
  const renderTitleSelection = () => {
    if (!outline || outline.titleSuggestions.length === 0) return null;

    return (
      <Card title="📝 选择文章标题" bordered={false} className="title-selection">
        <Space direction="vertical" style={{ width: '100%' }}>
          {outline.titleSuggestions.map((title, index) => (
            <Card
              key={index}
              hoverable
              className={`title-option ${selectedTitle === index ? 'selected' : ''}`}
              onClick={() => setSelectedTitle(index)}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                {selectedTitle === index && <CheckCircleOutlined style={{ color: '#52c41a' }} />}
                <span style={{ fontSize: '16px', fontWeight: selectedTitle === index ? 600 : 400 }}>
                  {title}
                </span>
              </div>
            </Card>
          ))}
        </Space>
      </Card>
    );
  };

  // 渲染提纲树
  const renderOutlineTree = () => {
    if (!outline) return null;

    return (
      <Card title="📋 提纲结构" bordered={false} className="outline-tree-card">
        <Tree
          showLine
          defaultExpandAll
          treeData={convertToTreeData(outline.nodes)}
          className="outline-tree"
        />
      </Card>
    );
  };

  // 渲染详细内容
  const renderDetailedContent = () => {
    if (!outline) return null;

    return (
      <Card title="📖 章节详情" bordered={false} className="outline-details">
        <Collapse accordion>
          {outline.nodes.map((node, index) => (
            <Panel
              header={
                <div>
                  <strong>{node.title}</strong>
                  <Tag style={{ marginLeft: 8 }} color="blue">
                    {node.estimatedWords}字
                  </Tag>
                </div>
              }
              key={node.id}
            >
              <div className="node-detail">
                {node.mainPoints && node.mainPoints.length > 0 && (
                  <div className="detail-section">
                    <div className="detail-label">主要论点:</div>
                    <ul>
                      {node.mainPoints.map((point, idx) => (
                        <li key={idx}>{point}</li>
                      ))}
                    </ul>
                  </div>
                )}

                {node.keywords && node.keywords.length > 0 && (
                  <div className="detail-section">
                    <div className="detail-label">关键词:</div>
                    <Space>
                      {node.keywords.map((kw) => (
                        <Tag key={kw} color="geekblue">
                          {kw}
                        </Tag>
                      ))}
                    </Space>
                  </div>
                )}

                {node.children && node.children.length > 0 && (
                  <div className="detail-section">
                    <div className="detail-label">子章节:</div>
                    <ul>
                      {node.children.map((child) => (
                        <li key={child.id}>
                          {child.title} ({child.estimatedWords}字)
                        </li>
                      ))}
                    </ul>
                  </div>
                )}
              </div>
            </Panel>
          ))}
        </Collapse>
      </Card>
    );
  };

  return (
    <div className="outline-panel">
      <div className="panel-header">
        <h2>📝 智能提纲生成</h2>
        <p className="panel-subtitle">
          AI将基于选中的观点自动生成文章提纲，帮助你快速建立清晰的写作框架
        </p>
      </div>

      {/* 统计信息 */}
      {renderStats()}

      {/* 控制面板 */}
      {renderControlPanel()}

      {/* 标题选择 */}
      {renderTitleSelection()}

      {/* 提纲树 */}
      {renderOutlineTree()}

      {/* 详细内容 */}
      {renderDetailedContent()}

      {/* 底部操作 */}
      {outline && (
        <div className="panel-footer">
          <Space>
            <Button size="large" onClick={() => window.history.back()}>
              返回观点
            </Button>
            <Button type="primary" size="large" onClick={onContinue}>
              开始写作
            </Button>
          </Space>
        </div>
      )}
    </div>
  );
};
